<?php
namespace frontend\models;

use frontend\models\Comment as comment_model;
use frontend\models\PostsCollect as p_collect_model;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Query;
use common\helps\tools;
use yii\db\Exception;
use common\helps\detection;

/**
 * Member model
 */
class Member extends ActiveRecord
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%member}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['mobile', 'password','username','head_img','city','birthday'], 'trim'],
            [['mobile', 'username','city_id','province_id','birthday'], 'required','message' => '{attribute}不能为空','on' => ['update_self_info']],
            [['head_img'], 'required','message' => '请上传{attribute}','on' => ['update_self_info']],
            [['mobile'], 'match', 'pattern' => '/^[1][3456789][0-9]{9}$/','message'=>'{attribute}值无效'],
            [['username'],'string','max'=>7, 'min'=>2, 'tooLong'=>'{attribute}请输入长度为2-7位字符', 'tooShort'=>'{attribute}请输入长度为2-7位字符'],
            [['id','sex','city_id'], 'match', 'pattern' => '/^[1-9][0-9]*$/','message'=>'{attribute}值无效'],
            [['username'], 'match', 'pattern' => '/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u','message'=>'{attribute}只能由汉字、字母、数字、下划线组成'],
        ];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '会员id',
            'username' => '昵称',
            'mobile'=>'手机号码',
            'head_img'=>'头像',
            'province_id'=>'省id',
            'city_id'=>'城市id',
            'birthday'=>'生日',
            'password'=>'密码',
            'experience'=>'经验值',
            'integral'=>'积分',
            'sex'=>'性别',
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [
                'id',
                //'username',
                'mobile',
                //'head_img',
                'password',
                'experience',
                'integral',
            ],
            'update_self_info'=>[
                'username',
                'head_img',
                'sex',
                'city_id',
                'province_id',
//                'birthday',
            ]
            ];

    }

    public static function addData($data = []){
        $model = new static();
        if(!empty($data['mobile'])){
            $model->mobile = $data['mobile'];
        }
        if(!empty($data['password'])){
            $model->password = $data['password'];
        }
        if(!empty($data['salt'])){
            $model->salt = $data['salt'];
        }
        if(!empty($data['username'])){
            $model->username = $data['username'];
        }
        if(!empty($data['province_id'])){
            $model->province_id = $data['province_id'];
        }
        if(!empty($data['city_id'])){
            $model->city_id = $data['city_id'];
        }
        return $model->save();
    }

    public static function saveData($id,$data){
        $model = static::findOne(['id' => $id]);
        if(empty($model)){
            return false;
        }
        if(!empty($data['token'])){
            $model->token = $data['token'];
        }
        if(!empty($data['integral'])){
            $model->integral = $data['integral'];
        }
        if(!empty($data['province_id'])){
            $model->province_id = $data['province_id'];
        }
        if(!empty($data['city_id'])){
            $model->city_id = $data['city_id'];
        }
        if(!empty($data['city'])){
            $model->city = $data['city'];
        }
        if(!empty($data['hry_member_id'])){
            $model->hry_member_id = $data['hry_member_id'];
        }
        return $model->save();
    }

    /**
     * @inheritdoc
     */
    public static function findOneData($field = '*',$data = [])
    {
        $query = new \yii\db\Query();
        $query->select([$field])->from('member');
        $query->where(['deleted_at' => null]);
        if(!empty($data['mobile'])){
            $query->andWhere(['mobile' => $data['mobile']]);
        }
        $command = $query->createCommand();
        $result = $command->queryOne();
        if(!empty($result['created_at']))
            $result['created_at'] = date('Y-m-d',$result['created_at']);
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }


    /**
     * 获取会员基本信息
     * @param $member_info
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getMemberInfo($member_info){
        $list=[];
        if(!empty($member_info['id'])){
            $redis = Yii::$app->cache;
            $list=json_decode($redis->hget('member_info' ,$member_info['token']),true);
            if(empty($list)){
                $list=$this->find()->select('id,username,mobile,head_img,experience,integral,sex,province_id,city_id,birthday,is_auth')->where(['id'=>intval($member_info['id'])])->asArray()->one();
                $redis->hset('member_info',$member_info['token'], json_encode($list));
            }
            //同时获取是否有新消息未读
            $notice_model = new Notice();
            $have_news = $notice_model->find()->where(['member_id'=>intval($member_info['id']),'status'=>1])->asArray()->one();
            if(!empty($have_news)){
                $list['has_new_msg'] = true;
            }else{
                $list['has_new_msg'] = false;
            }
        }
        return empty($list)?array():$list;

    }


    /**
     * 获取会员消息列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getNoticeList($params){
        $list=[];
        if(!empty($params['member_id'])){
            $list = (new Query())->select(
                    'notice.id as notice_id,notice.comment as notice_comment,FROM_UNIXTIME(notice.created_at) as created_at,notice.type as notice_type,notice.status as notice_status,notice.check_status,notice.check_msg,
                    posts.id as posts_id,posts.img as posts_img,posts.title as posts_title,posts.status as posts_status,posts.deleted_at as posts_del_status,
                    member.id as comment_member_id, member.username as comment_username, member.head_img'
                    )
                ->from('notice')
                ->innerJoin('posts','notice.posts_id=posts.id')
                ->leftJoin('member','notice.at_member_id=member.id')
                ->where(['notice.member_id'=>intval($params['member_id']),'notice.deleted_at'=>null])
                ->orderBy('notice.updated_at desc')
                ->all();
        }
        $list = tools::getPageData($list,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        if(count($list['data'])){
            foreach($list['data'] as &$value){
                if(empty($value['posts_del_status'])){
                    $value['posts_del_status'] = 1 ; //帖子未被删除
                }else{
                    $value['posts_del_status'] = 2; //帖子已被删除
                }
            }
        }


        return empty($list)?array():$list;

    }


    /**
     * 获取会员消息列表
     * @param $member_id
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function updateMemberNoticeStatus($member_id){
        $notice_model = new Notice();
        $notice_model::updateAll(['status' => 2],['member_id'=>$member_id]);
        return true;

    }


    /**
     * 获取会员评论列表
     * @param $member_info
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getMemberCommentList($member_info){
        $list=[];
        if(!empty($member_info['id'])){
            $list = (new Query())->select(
                'comment.id as comment_id,comment.comment as comment_describe,FROM_UNIXTIME(comment.created_at) as created_at,
                posts.id as posts_id,posts.img as posts_img,posts.title as posts_title,posts.describe as posts_describe,posts.deleted_at as posts_deleted_type,
                member.id as comment_member_id, member.username as comment_username, member.head_img as comment_user_head_img'
                 )
                ->from('comment')
                ->innerJoin('posts','comment.posts_id=posts.id')
                ->innerJoin('member','member.id=comment.member_id')
                ->where(['comment.member_id'=>intval($member_info['id']),'comment.deleted_at'=>null,'comment.status'=>3])
                ->orderBy('comment.updated_at DESC')
                ->all();
        }
        return empty($list)?array():$list;

    }

    /**
     * 获取会员收藏列表
     * @param $params
     * @param $member_info
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getMemberCollectList($params,$member_info){
        $list=[];
        if(!empty($member_info['id'])){
            $condition=['posts_collect.deleted_at'=>null,'is_collect'=>1,'posts_collect.member_id'=>$member_info['id']];
            if(!empty($params['type']) && intval($params['type'])==1){ // 1 项目
                $condition=['and',['posts_collect.deleted_at'=>null,'is_collect'=>1],['>','posts_collect.item_id',0],['posts_collect.member_id'=>$member_info['id']]];
            }elseif(!empty($params['type']) && intval($params['type'])==2){ // 2 帖子
                $condition=['and',['posts_collect.deleted_at'=>null,'is_collect'=>1],['>','posts_collect.posts_id',0],['posts_collect.member_id'=>$member_info['id']]];
            }

            $list = (new Query())->select(
                'posts_collect.item_id,posts_collect.is_like,posts_collect.member_id as collect_member_id,FROM_UNIXTIME(posts_collect.created_at) as created_at,
                 new_project.title as project_name,new_project.introduction,new_project.tags,new_project.tags,new_project.pic as project_pic,new_project.status as project_status,FROM_UNIXTIME(new_project.release_time) as release_time,
                 posts.id as posts_id,posts.img as posts_img,posts.title as posts_title,posts.describe as posts_describe,FROM_UNIXTIME(posts.created_at) as created_at, posts.deleted_at as posts_status,
                 member.username as username, member.head_img'
            )
                ->from('posts_collect')
                ->leftJoin('new_project','posts_collect.item_id=new_project.id')
                ->leftJoin('posts','posts_collect.posts_id=posts.id')
                ->leftJoin('member','member.id=posts.set_posts_id')
                ->where($condition)
                ->orderBy('posts_collect.id desc')
                ->all();
            $list = tools::getPageData($list,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
            if(count($list['data'])){
                $comment_model =new comment_model();
                $posts_collect_model =new p_collect_model();
                foreach($list['data'] as &$value){  // 处理帖子相关的评论、点赞、收藏数据
                    $value['is_like'] = intval($value['is_like']);
                    if($value['item_id']>0){ //项目
                        $value['type']=1;
                        $actor_model = new ProjectActor();
                        $tags_model = new ProjectType();
                        $value['actor_list'] =$actor_model->find()->select('name')->where(['project_id'=>$value['item_id']])->asArray()->all(); //项目演职人员
                        $tags = unserialize($value['tags']);
                        $value['tags'] =$tags_model->find()->select('title')->where(['in','id',$tags])->asArray()->all(); //项目标签类型
                    }else{ //帖子
                        $value['posts_img']=explode(',',$value['posts_img']);
                        $value['type']=2;
                        $value['comment_num'] = $comment_model->find()->where(['posts_id'=>$value['posts_id'],'deleted_at'=>null,'status'=>3])->asArray()->count();
                        $value['like_num'] = $posts_collect_model->find()->where(['posts_id'=>$value['posts_id'],'deleted_at'=>null,'is_like'=>1])->asArray()->count();
                        if($value['posts_status']>0){
                            $value['posts_status']=2;  //删除
                        }else{
                            $value['posts_status']=1; // 未删除
                        }
                    }

                }
            }

        }
        return empty($list)?array():$list;

    }



    /**
     * 会员删除评论列表
     * @param $params
     * @param $member_info
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function deleteMemberComment($params,$member_info){
        $t = static::getDb()->beginTransaction();
        try {
            $comment_model= new Comment();
            $model = $comment_model::findOne(['id' =>intval($params['comment_id']),'member_id'=>intval($member_info['id'])]);
            if(empty($model)) return array('error'=>'抱歉你没有权限删除该数据');
            $data['deleted_at']=time();
            $model->setAttributes($data, false);
            if (!$model->save()) {
                $t->rollBack();
                return array('error'=>'操作失败');
            }
            $model->refresh();
            $t->commit();
            return $model;
        } catch (Exception $e) {
            $t->rollback();
            return array('error'=>'操作失败');
        }

    }






    /**
     * 编辑会员基本信息
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function editMemberInfo($params){
        $t = static::getDb()->beginTransaction();
        try {
            $model           = static::findOne(['id' =>intval($params['member_id'])]);
            if(empty($model)) return array('error'=>'未查询到用户信息');
            if(!empty($params['username'])){
                $have_username = $this->find()->where(['username' =>$params['username']])->andWhere(['<>','id', intval($params['member_id'])])->asArray()->one();
                if(!empty($have_username)) return array('error'=>'用户名已存在！');
                //检测用户名的敏感词
                $detection = new detection();
                $check_res=$detection->checkWord($params['username']);
                if($check_res['errcode']!=0){
                    return array('error'=>'昵称含有敏感词汇');
                }
                $check_other_words=tools::checkOtherWords(trim($params['username']));
                if($check_other_words!==false){
                    return array('error'=>'昵称含有敏感词汇');
                }
            }
            if(intval($model->is_first_edit)<1){
                $task = new Task();
                $int = new IntLog();
                $task_info = $task::findOne(['id' =>FIRST_EDIT_INFO]);
                $idata = [
                    'member_id' => intval($params['member_id']),
                    'task_id' => $task_info['id'],
                    'int' => $task_info['integral'],
                    'type' => 1,
                ];
                $int::addData($idata);
                $params['integral']=empty($model->integral)?0:intval($model->integral);
                $params['integral']+=$task_info['integral'];
                $params['is_first_edit']=1;
            }

            $model->scenario = 'update_self_info';
            $token=$params['token'];
            unset($params['id']);
            unset($params['token']);
            $model->setAttributes($params, false);
            if (!$model->save()) {
                $t->rollBack();
                return array('error'=>'操作失败');
            }
            $model->refresh();
            $t->commit();
            $redis = Yii::$app->cache;
            $redis->hdel('member_info',$token);
            return $model;
        } catch (Exception $e) {
            $t->rollback();
            return array('error'=>'操作失败');
        }

    }



}
